package com.aaa.controller;

import com.aaa.entity.LayData;
import com.aaa.util.ConfigUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.UUID;

@Controller
public class UploadController {


    @PostMapping("uploadFile")
    public String uploadFile(MultipartFile file, HttpServletRequest request){
        // file 代表的是上传的文件
        // MultipartFile的别名必须跟input type=file里面的name的属性值保持完全一致
        // <input type="file" name="file"/>
        String oldname=file.getOriginalFilename();
        System.out.println("file = " + file.getOriginalFilename());

        String realPath = request.getServletContext().getRealPath("/upload");
        System.out.println("realPath = " + realPath);
        File file1 = new File(realPath);


        if(!file1.exists()){
            file1.mkdirs();
        }


        // 新的名字
        String s = UUID.randomUUID().toString();// DJKAHGFJSHGHKFSHKJDFG
        // 无标题.png  1.3.4.5.jpg
        // +.JPG  PNG JEPG
        // 获取原来的文件的后缀 oldname
        int i = oldname.lastIndexOf(".");
        String suffixname = oldname.substring(i);
        System.out.println("suffixname = " + suffixname);
        String newname=s+suffixname;
        System.out.println("newname = " + newname);


        // 将图片 上传到
        try {
            // 输出流  主要用于写入
            OutputStream outputStream = new FileOutputStream(file1+File.separator+newname);

            // 输入流
            InputStream inputStream = file.getInputStream();
            //
            int len=0;
            while((len=inputStream.read())!=-1){
                outputStream.write(len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            // 路径保存到数据库即可
            String picpath=realPath+File.separator+newname;


        } catch (Exception e) {
            e.printStackTrace();
        }

        return "main";
    }


    @PostMapping("uploadFile2")
    public String uploadFile2(MultipartFile file, HttpServletRequest request){
        // file 代表的是上传的文件
        // MultipartFile的别名必须跟input type=file里面的name的属性值保持完全一致
        // <input type="file" name="file"/>
        String oldname=file.getOriginalFilename();
        //System.out.println("file = " + file.getOriginalFilename());

        String realPath = request.getServletContext().getRealPath("/upload");
        System.out.println("realPath = " + realPath);
        File file1 = new File(realPath);


        if(!file1.exists()){
            file1.mkdirs();
        }


        // 新的名字
        String s = UUID.randomUUID().toString();// DJKAHGFJSHGHKFSHKJDFG
        // 无标题.png  1.3.4.5.jpg
        // +.JPG  PNG JEPG
        // 获取原来的文件的后缀 oldname
        int i = oldname.lastIndexOf(".");
        String suffixname = oldname.substring(i);
        //System.out.println("suffixname = " + suffixname);
        String newname=s+suffixname;
        //System.out.println("newname = " + newname);


        File file2 = new File(realPath+File.separator+newname);
        try {
            file.transferTo(file2);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String picpath=realPath+File.separator+newname;

        return "main";
    }

     @PostMapping("uploadFile3")
     @ResponseBody
    public LayData uploadFile3(MultipartFile file, HttpServletRequest request){

         // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
         String endpoint = ConfigUtil.END_POINT;
         // oss-cn-beijing.aliyuncs.com
         // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
         String accessKeyId = ConfigUtil.ACCESS_KEY_ID;
         String accessKeySecret =ConfigUtil.ACCESS_KEY_SECRET;
         // 填写Bucket名称，例如examplebucket。
         String bucketName = ConfigUtil.BUCKET_NAME;
         // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
         // 新的名字
         String s = UUID.randomUUID().toString();// DJKAHGFJSHGHKFSHKJDFG
         // 无标题.png  1.3.4.5.jpg
         // +.JPG  PNG JEPG
         // 获取原来的文件的后缀 oldname
         String oldname=file.getOriginalFilename();
         int i = oldname.lastIndexOf(".");
         String suffixname = oldname.substring(i);
         //System.out.println("suffixname = " + suffixname);
         String newname=s+suffixname;
         //System.out.println("newname = " + newname);

         String objectName = newname;
         // 创建OSSClient实例。
         OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
         try {
             // 创建PutObjectRequest对象。
             PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());
             // 上传字符串。
             ossClient.putObject(putObjectRequest);

         }  catch (Exception e) {
             e.printStackTrace();
         } finally {
             if (ossClient != null) {
                 ossClient.shutdown();
             }
         }
         String picpath="https://"+bucketName+"."+endpoint+"/"+objectName;
       // return "index";
         return new LayData(picpath);
    }

}
